package com.rain.cy.business.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.rain.cy.business.model.entity.UserEntity;
import com.rain.cy.business.service.UserScoreService;
import com.rain.cy.business.service.UserService;
import com.rain.cy.framework.entity.BaseController;
import com.rain.cy.framework.result.ErrorCodeEnum;
import com.rain.cy.framework.result.Result;
import com.rain.cy.framework.result.ResultUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangyulin
 * @since 2020-06-01
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private UserService userService;


    /**
     * 0、链接中携带base64加密的手机号，通过链接进入落地页，并查询用户信息
     * 1、通过base64加密的手机号 查询用户信息，
     * 1.1、若未返回code!=200 提示message中的内容 其他接口类似
     * 2、返回用户信息中包含用户的Id 基本信息 身份等
     * 3、可以将用户信息存在本地localStore中不过期，若被清除之后告知链接已失效
     * 4、可以将用户身份存为全局boolean类型的变量 isDoctor:true，方便页面中使用
     * 5、所有请求时请求头需带上userId 如下
     * {
     * userId:4
     * }
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取患者或者医生的详细信息", response = Result.class, notes = "yu_chen")
    public Result getUserInfo(String phoneBase64) {
        String phone = null;
        try {
            phone = new String(SecureUtil.decode(phoneBase64));
        } catch (Exception e) {
            log.error("手机号解析失败:" + phoneBase64);
        }
        if (StringUtils.isEmpty(phone)) {
            return ResultUtil.fail(ErrorCodeEnum.UnAuth);
        }
        UserEntity userEntity = userService.lambdaQuery()
                .eq(UserEntity::getPhone, phone)
                .last("limit 1").one();
        if (ObjectUtil.isNull(userEntity)) {
            return ResultUtil.fail(ErrorCodeEnum.CellPhoneHasNotRegister);
        }
        Map<Integer, UserEntity> doctorMap = userService.getDoctorMap();
        if (userEntity.getUserType()==1){

            userEntity.setConfig(doctorMap.get(userEntity.getDoctorId()).getConfig());
        }
        return ResultUtil.success(userEntity);
    }


}

